package com.example.tongyao.system.controller;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.tongyao.common.SuperController;
import com.example.tongyao.system.entity.*;
import com.example.tongyao.system.message.SystemMessage;
import com.example.tongyao.system.service.ISysDeptService;
import com.example.tongyao.system.service.ISysUserDeptService;
import com.example.tongyao.system.service.ISysUserService;
import com.example.tongyao.utils.*;
import com.example.tongyao.utils.token.UserUtils;
import com.example.tongyao.utils.tongyao.TyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

/**
 * <p>
 * 部门表 前端控制器
 * </p>
 *
 * @author tongyao
 * @since 2021-08-18
 */
@RestController
@Api(tags = "系统_部门前端控制器")
@RequestMapping("/system/sys-dept")
public class SysDeptController extends SuperController {


    @Resource
    private ISysDeptService iSysDeptService;

    @Resource
    private ISysUserDeptService iSysUserDeptService;

    @Resource
    private ISysUserService iSysUserService;

    /**
     * 查询部门列表
     * @return
     */
    /*@ApiOperation(
            value = "查询部门列表",
            notes = "查询自己的或所有的部门列表",
            httpMethod = "GET")
    @GetMapping(value = "/deptTree" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult deptTree() {
        *//**
         * 缺少数据范围操作 注
         *//*
        SysUser sysUser = (SysUser) UserUtils.getUserInfo();

        int i = 0;
        List<SysDept> sysDeptList = SysDeptController.showTree(iSysDeptService.list());

        return DataResult.setSuccess(sysDeptList);
    }*/



    @ApiOperation(
            value = "查询部门",
            notes = "分页根据部门父级查询部门子级列表",
            httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptId",value = "父级deptId",required = true),
            @ApiImplicitParam(name = "pageNo",value = "当前页数",defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize",value = "显示条数",defaultValue = "10"),
            @ApiImplicitParam(name = "sortBy",value = "排序字段（多个以英文逗号拼接）",defaultValue = "create_time"),
            @ApiImplicitParam(name = "order",value = "排序类型",defaultValue = "asc")
    })
    @GetMapping(value = "/page" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult page(@RequestParam(required = false)  String deptId,
                               @RequestParam(defaultValue = "1") int pageNo,
                               @RequestParam(defaultValue = "10") int pageSize,
                               @RequestParam(defaultValue = "create_time") String sortBy,
                               @RequestParam(defaultValue = "asc") String order) {
        PageUtil<SysDept> page = new PageUtil<>(pageNo,pageSize,sortBy,order);
        Map<String, Object> params = TyUtils.toObjectMap(page);
        params.put("deptId",deptId);

        List<SysDept> list = iSysDeptService.deptPage(params);
        page.setPage(list,list.size(),pageNo);
        return DataResult.setSuccess(page);
    }


    @ApiOperation(
            value = "添加部门",
            notes = "添加一个部门",
            httpMethod = "POST")
    @PostMapping(value = "/save" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult save(@Valid @RequestBody(required = true) SysDept sysDept) {

        codeExist(sysDept.getDeptCode());
        SysUser user = (SysUser) UserUtils.getUserInfo();

        sysDept.setDelFlag(1);
        sysDept.setDeptEnabled(true);
        sysDept.setCreateBy(user.getUserId());
        sysDept.setCreateTime(DateUtils.getDateTime());

        iSysDeptService.save(sysDept);
        if(!reuslt){
            throw new RuntimeException("部门添加失败！");
        }
        return DataResult.setSuccess(null);
    }


    @ApiOperation(
            value = "编辑部门",
            notes = "编辑一个部门",
            httpMethod = "PUT")
    @PutMapping(value = "/edit" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult edit(@Valid @RequestBody(required = true) SysDept sysDept) {

        SysUser user = (SysUser) UserUtils.getUserInfo();

        LambdaUpdateWrapper<SysDept> sysDeptLambdaUpdateWrapper = new LambdaUpdateWrapper<>();

        /*if(StringUtils.isNotBlank(sysDept.getParentId())){
            sysDeptLambdaUpdateWrapper.set(SysDept::getParentId,sysDept.getParentId());

        }else*/
        if(StringUtils.isNotBlank(sysDept.getDeptName())){
            sysDeptLambdaUpdateWrapper.set(SysDept::getDeptName,sysDept.getDeptName());
        }
        if(StringUtils.isNotBlank(sysDept.getDeptCode())){
            codeExist(sysDept.getDeptCode());
            sysDeptLambdaUpdateWrapper.set(SysDept::getDeptName,sysDept.getDeptCode());
        }
        if(StringUtils.isNotBlank(sysDept.getDeptDesc())){
            sysDeptLambdaUpdateWrapper.set(SysDept::getDeptDesc,sysDept.getDeptDesc());
        }
        if(StringUtils.isNotBlank(sysDept.getLeader())){
            sysDeptLambdaUpdateWrapper.set(SysDept::getLeader,sysDept.getLeader());
        }
        if(StringUtils.isNotBlank(sysDept.getLeaderPhone())){
            sysDeptLambdaUpdateWrapper.set(SysDept::getLeaderPhone,sysDept.getLeaderPhone());
        }
        if(StringUtils.isNotNull(sysDept.getSort())){
            sysDeptLambdaUpdateWrapper.set(SysDept::getLeaderPhone,sysDept.getSort());
        }



        sysDeptLambdaUpdateWrapper.set(SysDept::getModifyBy,user.getUserId());
        sysDeptLambdaUpdateWrapper.set(SysDept::getModifyTime,DateUtils.getDateTime());

        sysDeptLambdaUpdateWrapper.eq(SysDept::getDeptId,sysDept.getDeptId());

        reuslt = iSysDeptService.update(sysDeptLambdaUpdateWrapper);
        if(!reuslt){
            throw new RuntimeException("部门编辑失败！");
        }
        return DataResult.setSuccess(null);
    }

    @ApiOperation(
            value = "删除部门",
            notes = "删除一个或多个部门",
            httpMethod = "DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptId",value = "部门编号，多个以英文逗号拼接",required = true),
    })
    @DeleteMapping(value = "/delete" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult delete(@RequestParam String deptId){

        //从配置里获取默认部门
        SysConfig sysConfig = iSysConfigService.getConfigByKey("sys_default_dept");
        if(StringUtils.isNull(sysConfig)){
            throw new RuntimeException("系统配置：${sys_default_dept} 为空！");
        }

        map = commonService.getOne(
                "dept_id",
                "sys_dept",
                "dept_code = '"+sysConfig.getConfigValue()+"' and del_flag = 1"
        );
        if(StringUtils.isNull(map)){
            throw new RuntimeException("属性值为：${"+sysConfig.getConfigValue()+"} 查询出来的数据为空！");
        }

        String mapDeptId = map.get("job_id").toString();
        if(mapDeptId.equals(deptId)){
            throw new RuntimeException("经系统设置，该部门不能删除！");
        }

        List deptIds = Arrays.asList(deptId.split(","));
        for (Object dept: deptIds) {

            //校验是否删除默认部门
            if(!mapDeptId.equals(dept)){
                //删除部门
                LambdaUpdateWrapper<SysDept> sysDeptLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                sysDeptLambdaUpdateWrapper
                        .set(SysDept::getDelFlag,"0")
                        .eq(SysDept::getDeptId,dept);
                reuslt = iSysDeptService.update(sysDeptLambdaUpdateWrapper);
                if(!reuslt){
                    throw new RuntimeException(
                            SystemMessage.dept+
                                    SystemMessage.delete+
                                    SystemMessage.fail+
                                    SystemMessage.a
                    );
                }

                //把用户部门关系部门字段替换成默认的
                LambdaUpdateWrapper<SysUserDept> sysUserDeptLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                sysUserDeptLambdaUpdateWrapper
                        .set(SysUserDept::getDeptId,mapDeptId)
                        .eq(SysUserDept::getDeptId,dept);
                reuslt = iSysUserDeptService.update(sysUserDeptLambdaUpdateWrapper);
                if(!reuslt){
                    throw new RuntimeException(
                            SystemMessage.user+
                                    SystemMessage.dept+
                                    SystemMessage.relation+
                                    SystemMessage.update+
                                    SystemMessage.fail+
                                    SystemMessage.a
                    );
                }

                /*//需新增删除用户的操作
                map = new HashMap<>();
                map.put("dept_id",dept);
                List<SysUserDept> sysUserDeptList = iSysUserDeptService.listByMap(map);
                for (SysUserDept sysUserdept: sysUserDeptList) {
                    //考虑是否可以复用用户控制器里的delete方法？
                    LambdaUpdateWrapper<SysUser> sysUserLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    sysUserLambdaUpdateWrapper
                            .set(SysUser::getDelFlag,"0")
                            .eq(SysUser::getUserId,sysUserdept.getUserId());
                    reuslt = iSysUserService.update(sysUserLambdaUpdateWrapper);
                    if(!reuslt){
                        throw new RuntimeException("用户部门关系删除失败！");

                    }
                }*/
            }

        }
        return DataResult.setSuccess(null);
    }


    @ApiOperation(
            value = "更改状态",
            notes = "更改部门的启用禁用状态",
            httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptId",value = "部门编号",required = true),
            @ApiImplicitParam(name = "state",value = "部门状态（true为启用，false为禁用）",required = true)
    })
    @PutMapping(value = "/changeState" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult changeState(
            @RequestParam String deptId,
            @RequestParam boolean state
    ){

        LambdaUpdateWrapper<SysDept> sysDeptLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        sysDeptLambdaUpdateWrapper
                .set(SysDept::isDeptEnabled,state)
                .eq(SysDept::getDeptId,deptId);
        reuslt = iSysDeptService.update(sysDeptLambdaUpdateWrapper);

        if(!reuslt){
            throw new RuntimeException(
                    SystemMessage.dept + SystemMessage.update + SystemMessage.fail + SystemMessage.a
            );
        }

        return DataResult.setSuccess(null);
    }



    /**
     * 参考 https://vue3.stylefeng.cn/
     * admin/123456
     */


    /**
     * 调整树的上下级
     *
     * @param deptList 部门
     * @return
     */
    public static List<SysDept> showTree(List<SysDept> deptList) {
        List<SysDept> nodeList = new ArrayList<SysDept>();
        for (SysDept dept : deptList) {
            boolean isChildMark = false;
            for (SysDept sysDept : deptList) {
                if (dept.getParentId() != null && dept.getParentId().equals(sysDept.getDeptId())) {
                    isChildMark = true;
                    if (sysDept.getChildren() == null) {
                        sysDept.setChildren(new ArrayList<SysDept>());
                    }
                    sysDept.getChildren().add(dept);
                    break;
                }
            }
            if (!isChildMark) {
                nodeList.add(dept);
            }
        }
        return nodeList;
    }



    /**
     * 判断部门编码是否存在
     * @param code
     * @return
     */
    public void codeExist(String code){
        int count = commonService.getCount("sys_dept","dept_code = '"+code+"' and del_flag = 1");
        if(count > 0){
            throw new RuntimeException(code+" 部门编码已存在！");
        }
    }
}
